import os
import pydicom
from PIL import Image


def convert_dcm_to_jpg(input_folder, output_folder):
    # 遍历文件夹中的所有文件
    for filename in os.listdir(input_folder):
        if filename.endswith('.dcm'):
            # 读取DCM文件
            dcm_path = os.path.join(input_folder, filename)
            ds = pydicom.dcmread(dcm_path)

            # 将像素数据转换为图像
            pixel_data = ds.pixel_array
            image = Image.fromarray(pixel_data)

            # 保存为JPG文件
            jpg_filename = os.path.splitext(filename)[0] + '.jpg'
            jpg_path = os.path.join(output_folder, jpg_filename)
            image.save(jpg_path)
            print(f"Converted {filename} to {jpg_filename}")


# 指定输入和输出文件夹
input_folder = "input"
output_folder = "output"

# 执行转换
convert_dcm_to_jpg(input_folder, output_folder)
